去除陣列中的黑名單(以物件屬性檢查)


Posted by mijouhsieh on 2022-03-31

players名單是陣列,陣列元素為物件,一個物件包含人名、信箱、彩券號碼。

規格

  1. 處理 players 陣列
    • 將登記在 backList 裡的項目,從 players 移除
    • 使用物件的 email 屬性檢查
  2. 使用 console.log(players) 印出處理後的陣列

複習

出錯部分

判段式 if (blackList.email.includes(players[i].email))
出錯部分
blackList陣列.email 沒有寫blackList陣列index,電腦會讀不到email屬性,所以語法.includes也就無法使用。

flowchart

  1. players陣列以for loop 一個個看有無blackList。
    順序由players陣列最後一個index往前檢查,可避免項目被刪除後,下一個項目的原index被修改(往前遞補)而造成未檢查到的情形,因此,index由大到小一一檢查項目就沒有此問題。
  2. 使用雙層loop來比較陣列中的物件

email-flowchart

coding

完成

為了方便觀察每次迴圈

  • 在for loop外加上 let n = 1 (為第一圈),在for loop底部加上 n ++ 下一圈,最後,顯示由index大到小跑完11次。
    以及 players[i] 和 blackList[j] 各自陣列元素的 "物件email屬性" 有相同的值時,console.log('match', players[i].email),也就是要被刪除的黑名單。
  • 使用雙層loop來比較陣列中的物件。
  • j < blackList.length取代 j < 2 ,讓寫法彈性,較好維護code。
  • 因為姓名有可能相同,所以用email檢查。
  • 找相同值可以用 === 或 array.includes()
  • players[i].email === blackList[j].email
  • players[i].email.includes(blackList[j].email)

語法

MDN Array.prototype.splice(要修改的index, (選)刪除陣列元素的數量, (選)要加入到陣列的元素)
splice() 方法可以藉由刪除既有元素並/或加入新元素來改變一個陣列的內容。

MDN Array.prototype.includes(searchElement要搜尋的元素, (選)開始搜尋 searchElement 的位置(預設值為 0))
includes() 方法會判斷陣列是否包含特定的元素,並以此來回傳 true 或 false。


#Array #includes #splice #blackList #=== #double for loop







Related Posts

How to build CICD with Jenkins as code based on container

How to build CICD with Jenkins as code based on container

Heroku 部署

Heroku 部署

[8] 進階資料型別 part3 - Set、Dict

[8] 進階資料型別 part3 - Set、Dict


Comments